package edu.purdue.cs.aggr.message;

import edu.purdue.cs.aggr.AggrException;
import edu.purdue.cs.aggr.Node;
import edu.purdue.cs.aggr.message.EventNotificationMessage.Event;

public class EventMessageBuilder {
	
	public static EventNotificationMessage createEventMessage(Node node, Event event, Object value) throws AggrException {
		return createEventMessage(node, event, node.getControllerId(), value);
	}
	
	public static EventNotificationMessage createEventMessage(Node node, Event event, String destination, Object value) throws AggrException {
		EventNotificationMessage message = new EventNotificationMessage();
		message.setEvent(event);
		message.setSender(node.getId());
		System.out.println("Creating event message from " + node.getId() + " | " + event + " | " + destination);
		
		if (event == Event.LEAF_DONE_PROCESSING || event == Event.UPDATE_DONE_PROCESSING) {
			populateLeafStartingToAggregateMessage(message, (Long) value);
		} else if (event == Event.ROOT_DONE) {
			populatRootDoneMessage(message);
		} else if (event == Event.AGGREGATE_COMMAND || event == Event.BEGINNING_UPDATE || event == Event.VERTEX_RECEIVED) {
			//nothing to be done.
		} else {
			throw new AggrException("Unknown event type");
		}
		message.setDestination(destination);
		return message;
	}

	private static void populatRootDoneMessage(EventNotificationMessage message) {
	}

	private static void populateLeafStartingToAggregateMessage(
			EventNotificationMessage message, Long time) {
		message.setTime(time);
	}
}
